<?php

/**
 * @category   MM
 * @package    MM_Service
 */
class MM_Service_Admin_EventSync extends Mediad2_Service_Abstract
{
	/**
	 * const
	 */
	const SYNCSTATUS_NO		= 0;	//不需要同步
	const SYNCSTATUS_YES	= 1;	//需要同步
	
	/**
	 * 初始化
	 */
	public function init()
	{
		$this->setMapper('MM_Mapper_EventSync');
		$this->setModel('MM_Model_EventSync');
	}
	
	/**
	 * 根据eid和synctime，同步活动信息
	 * @param array $params
	 */
	public function sync(array $sqlparams)
	{
		try {
			$data = null;
			foreach ($sqlparams as $key=>$param) {
				
				$eid = $param['eid'];
				$synctime = $param['synctime'];
				
				//定义返回数据
				$syncdata = array(
						'eid'		=> $eid,
						'status' 	=> self::SYNCSTATUS_NO,
						'data'		=> null,
				);
				
				//判断是否需要同步
				$isNeedSync = $this->isNeedSync($eid, $synctime);
				if ($isNeedSync == false) {
					$syncdata['status'] = self::SYNCSTATUS_NO;
					$data[] = $syncdata;
					continue;
				}
				
				//设置同步状态
				$syncdata['status'] = self::SYNCSTATUS_YES;
				
				//获取event_sync
				$where = "eid = $eid AND modifytime > $synctime";
				$result = $this->fetchAll(null,null,$where);
				if ($result->getData()==Mediad2_Model_Result::CODE_FAILURE) {
					return $result;
				}
				$arrSyncTable = $result->getData();
				
				//循环获取event_sync_record
				foreach ($arrSyncTable as $key => $eventSync) {
				
					$table = $eventSync->getTable();			//同步表名
					$modifytype = $eventSync->getModifytype();	//同步类型
				
					//根据同步类型，获取同步SQL
					$sqlparams = array(
							'eid' 		=> $eid,
							'table'		=> $table,
							'modifytype'=> $modifytype,
							'modifytime'=> $synctime,
					);
					$sql = $this->getSyncSql($sqlparams);
				
					//获取同步数据
					$arrSyncData = $this->querySQL($sql);
				
					//封装packet
					$packet = new MM_Model_SyncPacket();
					$packet->setTable($table);
					$packet->setModifytype($modifytype);
					$packet->setRowNum(count($arrSyncData));
					$packet->setRows($arrSyncData);
				
					//设置同步数据
					$syncdata['data'][] = $packet->toArray();
				}
				
				$data[] = $syncdata;
				
			} 
			
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
		
		} catch(Zend_Exception $e) {
		
			//出错处理
			$this->handleException($e);
		
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
		
	}
	
	//---------------------------------------------------
	// 私有方法
	//---------------------------------------------------
	/**
	 * 判断指定的活动是否需要同步
	 * @param int $eid
	 * @param int $synctime
	 * @return boolean 
	 */
	private function isNeedSync($eid, $synctime)
	{
		$isNeedSync = false;
		$where = "eid = $eid and modifytime > $synctime";
		$mapper = $this->getMapper();
		$count = $mapper->getCount($where);
		if ($count > 0) $isNeedSync = true;
		return $isNeedSync;
	}
	
	/**
	 * querySQL语句
	 * @param string $sql
	 * @return array mixed data return an array containing all of the result set rows
	 */
	private function querySQL($sql)
	{
		//获得db对象
		$db = $this->getMapper()->getDao()->getAdapter();
		
		//准备statement
		$stmt = $db->query($sql);
	
		//使用PDOStatement对象$stmt将所有结果数据放到一个数组$result中，并返回$result
		$result = $stmt->fetchAll();
		return $result;
	}
	
	/**
	 * 根据同步表名和类型，获取同步SQL
	 * @param array $params
	 * @return string $sql
	 */
	public function getSyncSql(array $params)
	{
		//var
		$eid = $params['eid'];
		$table = $params['table'];
		$modifytype = $params['modifytype'];
		$modifytime = $params['modifytime'];
				
		//定义sqlSyncRecord
		$sqlSyncRecord = "select esr.modifyrowid from event_sync_record esr ";
		$whereSyncRecord = sprintf(" where esr.eid = %u and esr.modifytime > %u and esr.table = '%s' and esr.modifytype = %u", $eid, $modifytime, $table, $modifytype);
		$orderSyncRecord = " order by id asc";
		$sqlSyncRecord = $sqlSyncRecord . $whereSyncRecord . $orderSyncRecord;
		
		//根据类型，定义sqlSync
		$sqlSync = '';
		switch ($modifytype) {
			case MM_Model_EventSync::MODIFYTYPE_DELETE:
				$sqlSync = $sqlSyncRecord;
				break;
			case MM_Model_EventSync::MODIFYTYPE_INSERT:
			case MM_Model_EventSync::MODIFYTYPE_UPDATE:
				$idname = $this->getRowidName($table);
				$sqlSync = "select * from $table where $idname in ($sqlSyncRecord)";
				break;
			default:
				break;
		}
		return $sqlSync;
	}
	
	/**
	 * 根据表名获取ID名称
	 * @param string table_name
	 * @return string rowid_name
	 */
	private function getRowidName($table)
	{
		$idname = 'id';
		switch ($table) {
			case 'event':
				$idname = 'eid';
				break;
			case 'event_address':
				$idname = 'eaid';
				break;
			case 'event_applause':
				$idname = 'eapid';
				break;
			case 'event_contact':
				$idname = 'ectid';
				break;
			case 'event_content':
				$idname = 'ecid';
				break;
			case 'event_files':
				$idname = 'fid';
				break;
			case 'event_guests':
				$idname = 'egid';
				break;
			case 'event_meta':
				$idname = 'emid';
				break;
			case 'event_schedule':
				$idname = 'esid';
				break;
			case 'event_schedule_meta':
				$idname = 'esmid';
				break;
			case 'event_speakers':
				$idname = 'espid';
				break;
			case 'event_venue':
				$idname = 'evid';
				break;
			case 'event_weibo':
				$idname = 'ewbid';
				break;
			default:
				break;
		}
		return $idname;
	}
	
}